import { Router, Request, Response } from 'express'
import { v4 as uuidv4 } from 'uuid'
import { getDatabase } from '../database/init'
import { authenticateToken } from '../middleware/auth'
import { normalizeDueDate, normalizeTimestamp } from '../utils/dateUtils'

const router = Router()

// 所有任务路由都需要认证
router.use(authenticateToken)

// 获取所有任务
router.get('/', async (req: Request, res: Response) => {
  try {
    const db = getDatabase()
    
    const result = await db.query(`
      SELECT t.*, 
             COALESCE(
               json_agg(
                 CASE WHEN s.id IS NOT NULL THEN 
                   json_build_object('id', s.id, 'title', s.title, 'completed', s.completed)
                 END
               ) FILTER (WHERE s.id IS NOT NULL), 
               '[]'
             ) as subtasks
      FROM tasks t
      LEFT JOIN subtasks s ON t.id = s.task_id
      WHERE t.user_id = $1
      GROUP BY t.id
      ORDER BY t.created_at DESC
    `, [req.userId])
    
    const tasks = result.rows.map((row: any) => {
      // 删除原始的下划线字段，避免冲突
      const { 
        due_date, created_at, updated_at, user_id,
        is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
        ...cleanRow 
      } = row
      
      return {
        ...cleanRow,
        dueDate: due_date,
        createdAt: created_at,
        updatedAt: updated_at,
        userId: user_id,
        isRecurring: is_recurring,
        recurringType: recurring_type,
        recurringPattern: recurring_pattern,
        parentRecurringId: parent_recurring_id
      }
    })
    
    res.json(tasks)
  } catch (error) {
    console.error('获取任务失败:', error)
    res.status(500).json({ error: '获取任务失败' })
  }
})

// 获取单个任务
router.get('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    const result = await db.query(`
      SELECT t.*, 
             COALESCE(
               json_agg(
                 CASE WHEN s.id IS NOT NULL THEN 
                   json_build_object('id', s.id, 'title', s.title, 'completed', s.completed)
                 END
               ) FILTER (WHERE s.id IS NOT NULL), 
               '[]'
             ) as subtasks
      FROM tasks t
      LEFT JOIN subtasks s ON t.id = s.task_id
      WHERE t.id = $1 AND t.user_id = $2
      GROUP BY t.id
    `, [id, req.userId])
    
    if (result.rows.length === 0) {
      return res.status(404).json({ error: '任务不存在或无权访问' })
    }
    
    const task = result.rows[0]
    const taskWithSubtasks = {
      ...task,
      dueDate: task.due_date,
      createdAt: task.created_at,
      updatedAt: task.updated_at
    }
    
    res.json(taskWithSubtasks)
  } catch (error) {
    console.error('获取任务失败:', error)
    res.status(500).json({ error: '获取任务失败' })
  }
})

// 创建新任务
router.post('/', async (req: Request, res: Response) => {
  try {
    const { 
      title, description, dueDate, reminderMinutes, priority, category, tags, notes, subtasks,
      isRecurring, recurringType, recurringPattern, status, boardPosition
    } = req.body
    
    if (!title) {
      return res.status(400).json({ error: '任务标题不能为空' })
    }
    
    const id = uuidv4()
    const now = normalizeTimestamp(new Date())
    const normalizedDueDate = normalizeDueDate(dueDate)
    
    const db = getDatabase()
    
    // 如果是重复任务，先创建重复任务模板
    let recurringTaskId = null
    if (isRecurring) {
      recurringTaskId = uuidv4()
      
      // 处理 recurringPattern - 确保是有效的 JSON 或 null
      let processedRecurringPattern = null
      if (recurringPattern) {
        try {
          // 如果是字符串，尝试解析为 JSON
          if (typeof recurringPattern === 'string') {
            processedRecurringPattern = recurringPattern.trim() ? JSON.parse(recurringPattern) : null
          } else {
            processedRecurringPattern = recurringPattern
          }
        } catch (error) {
          // 如果解析失败，将字符串作为简单对象存储
          processedRecurringPattern = { pattern: recurringPattern }
        }
      }
      
      await db.query(`
        INSERT INTO recurring_tasks (
          id, title, description, priority, category, tags, notes, user_id,
          recurring_type, recurring_pattern, is_active, created_at, updated_at
        ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13)
      `, [
        recurringTaskId, title, description, priority || 'P2', 
        category || 'work', tags || [], notes, req.userId, recurringType, 
        processedRecurringPattern, true, now, now
      ])
    }
    
    // 创建任务实例
    // 处理 tasks 表中的 recurringPattern - 如果是空字符串则设为 null
    const taskRecurringPattern = recurringPattern && recurringPattern.trim() ? recurringPattern : null
    
    await db.query(`
      INSERT INTO tasks (
        id, title, description, due_date, reminder_minutes, priority, category, tags, notes, user_id,
        is_recurring, recurring_type, recurring_pattern, parent_recurring_id,
        status, board_position, created_at, updated_at
      ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14, $15, $16, $17, $18)
    `, [
      id, title, description, normalizedDueDate, reminderMinutes || 30, priority || 'P2', category || 'work', 
      tags || [], notes, req.userId, isRecurring || false, recurringType, taskRecurringPattern, 
      recurringTaskId, status || 'todo', boardPosition || 0, now, now
    ])
    
    // 如果是重复任务，创建实例关联记录
    if (isRecurring && recurringTaskId) {
      const instanceId = uuidv4()
      const dueDateStr = normalizedDueDate ? normalizedDueDate.split('T')[0] : new Date().toISOString().split('T')[0]
      
      await db.query(`
        INSERT INTO recurring_task_instances (id, recurring_task_id, task_id, due_date, created_at)
        VALUES ($1, $2, $3, $4, $5)
      `, [instanceId, recurringTaskId, id, dueDateStr, now])
    }
    
    // 创建子任务
    if (subtasks && subtasks.length > 0) {
      for (const subtask of subtasks) {
        await db.query(`
          INSERT INTO subtasks (id, task_id, title, completed)
          VALUES ($1, $2, $3, $4)
        `, [uuidv4(), id, subtask.title, subtask.completed || false])
      }
    }
    
    // 返回完整的任务数据
    const createdTask = {
      id,
      title,
      description,
      dueDate: normalizedDueDate,
      priority: priority || 'P2',
      category: category || 'work',
      tags: tags || [],
      completed: false,
      notes,
      status: status || 'todo',
      boardPosition: boardPosition || 0,
      isRecurring: isRecurring || false,
      recurringType,
      recurringPattern: taskRecurringPattern,
      parentRecurringId: recurringTaskId,
      reminderMinutes: reminderMinutes || 30,
      createdAt: now,
      updatedAt: now,
      userId: req.userId,
      subtasks: subtasks || []
    }
    
    res.status(201).json(createdTask)
  } catch (error) {
    console.error('创建任务失败:', error)
    res.status(500).json({ error: '创建任务失败' })
  }
})

// 更新任务
router.put('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const { title, description, dueDate, priority, category, tags, notes, subtasks, status } = req.body
    
    // 验证必填字段 - 只在title存在时才验证
    if (title !== undefined && (!title || title.trim() === '')) {
      return res.status(400).json({ error: '任务标题不能为空' })
    }
    
    const db = getDatabase()
    
    // 检查任务是否存在且属于当前用户
    const checkResult = await db.query('SELECT id FROM tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (checkResult.rows.length === 0) {
      return res.status(404).json({ error: '任务不存在或无权访问' })
    }
    
    // 更新任务 - 支持部分更新
    const now = normalizeTimestamp(new Date())
    
    // 构建动态更新语句
    const updates = []
    const values = []
    let paramIndex = 1
    
    if (title !== undefined) {
      updates.push(`title = $${paramIndex}`)
      values.push(title)
      paramIndex++
    }
    if (description !== undefined) {
      updates.push(`description = $${paramIndex}`)
      values.push(description)
      paramIndex++
    }
    if (dueDate !== undefined) {
      updates.push(`due_date = $${paramIndex}`)
      values.push(normalizeDueDate(dueDate))
      paramIndex++
    }
    if (priority !== undefined) {
      updates.push(`priority = $${paramIndex}`)
      values.push(priority)
      paramIndex++
    }
    if (category !== undefined) {
      updates.push(`category = $${paramIndex}`)
      values.push(category)
      paramIndex++
    }
    if (tags !== undefined) {
      updates.push(`tags = $${paramIndex}`)
      values.push(tags || [])
      paramIndex++
    }
    if (notes !== undefined) {
      updates.push(`notes = $${paramIndex}`)
      values.push(notes)
      paramIndex++
    }
    if (status !== undefined) {
      updates.push(`status = $${paramIndex}`)
      values.push(status)
      paramIndex++
    }
    
    // 总是更新 updated_at
    updates.push(`updated_at = $${paramIndex}`)
    values.push(now)
    paramIndex++
    
    // 添加 WHERE 条件的参数
    values.push(id, req.userId)
    
    if (updates.length > 1) { // 除了 updated_at，还有其他字段要更新
      await db.query(`
        UPDATE tasks 
        SET ${updates.join(', ')}
        WHERE id = $${paramIndex} AND user_id = $${paramIndex + 1}
      `, values)
    }
    
    // 更新子任务
    if (subtasks) {
      // 删除旧的子任务
      await db.query('DELETE FROM subtasks WHERE task_id = $1', [id])
      
      // 插入新的子任务
      if (subtasks.length > 0) {
        for (const subtask of subtasks) {
          await db.query(`
            INSERT INTO subtasks (id, task_id, title, completed)
            VALUES ($1, $2, $3, $4)
          `, [uuidv4(), id, subtask.title, subtask.completed || false])
        }
      }
    }
    
    res.json({ message: '任务更新成功' })
  } catch (error) {
    console.error('更新任务失败:', error)
    res.status(500).json({ error: '更新任务失败' })
  }
})

// 删除任务
router.delete('/:id', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    // 检查任务是否存在且属于当前用户
    const checkResult = await db.query('SELECT id FROM tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    if (checkResult.rows.length === 0) {
      return res.status(404).json({ error: '任务不存在或无权访问' })
    }
    
    // 删除任务（子任务会通过外键约束自动删除）
    await db.query('DELETE FROM tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    
    res.json({ message: '任务删除成功' })
  } catch (error) {
    console.error('删除任务失败:', error)
    res.status(500).json({ error: '删除任务失败' })
  }
})

// 切换任务完成状态
router.patch('/:id/toggle', async (req: Request, res: Response) => {
  try {
    const { id } = req.params
    const db = getDatabase()
    
    console.log(`[DEBUG] Toggle请求 - 任务ID: ${id}, 用户ID: ${req.userId}`)
    
    // 检查任务是否存在且属于当前用户
    const checkResult = await db.query('SELECT id FROM tasks WHERE id = $1 AND user_id = $2', [id, req.userId])
    console.log(`[DEBUG] 任务查询结果: ${checkResult.rows.length} 条记录`)
    
    if (checkResult.rows.length === 0) {
      console.log(`[DEBUG] 任务不存在或无权访问 - 任务ID: ${id}, 用户ID: ${req.userId}`)
      return res.status(404).json({ error: '任务不存在或无权访问' })
    }
    
    // 切换完成状态
    const now = normalizeTimestamp(new Date())
    await db.query('UPDATE tasks SET completed = NOT completed, updated_at = $1 WHERE id = $2 AND user_id = $3',
      [now, id, req.userId])
    
    res.json({ message: '任务状态更新成功' })
  } catch (error) {
    console.error('更新任务状态失败:', error)
    res.status(500).json({ error: '更新任务状态失败' })
  }
})

// ========== 子任务管理 API ==========

// 获取任务的所有子任务
router.get('/:taskId/subtasks', async (req: Request, res: Response) => {
  try {
    const { taskId } = req.params
    const db = getDatabase()
    
    // 检查任务是否存在
    const taskCheck = await db.query('SELECT id FROM tasks WHERE id = $1', [taskId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '任务不存在' })
    }
    
    const result = await db.query(`
      SELECT id, task_id, title, completed
      FROM subtasks 
      WHERE task_id = $1
      ORDER BY id ASC
    `, [taskId])
    
    res.json(result.rows)
  } catch (error) {
    console.error('获取子任务失败:', error)
    res.status(500).json({ error: '获取子任务失败' })
  }
})

// 创建新子任务
router.post('/:taskId/subtasks', async (req: Request, res: Response) => {
  try {
    const { taskId } = req.params
    const { title } = req.body
    
    if (!title) {
      return res.status(400).json({ error: '子任务标题不能为空' })
    }
    
    const db = getDatabase()
    
    // 检查任务是否存在
    const taskCheck = await db.query('SELECT id FROM tasks WHERE id = $1', [taskId])
    if (taskCheck.rows.length === 0) {
      return res.status(404).json({ error: '任务不存在' })
    }
    
    const subtaskId = uuidv4()
    
    await db.query(`
      INSERT INTO subtasks (id, task_id, title, completed)
      VALUES ($1, $2, $3, $4)
    `, [subtaskId, taskId, title, false])
    
    res.status(201).json({ 
      id: subtaskId,
      task_id: taskId,
      title,
      completed: false,
      message: '子任务创建成功' 
    })
  } catch (error) {
    console.error('创建子任务失败:', error)
    res.status(500).json({ error: '创建子任务失败' })
  }
})

// 更新子任务
router.put('/subtasks/:subtaskId', async (req: Request, res: Response) => {
  try {
    const { subtaskId } = req.params
    const { title, completed } = req.body
    
    if (!title) {
      return res.status(400).json({ error: '子任务标题不能为空' })
    }
    
    const db = getDatabase()
    
    // 检查子任务是否存在
    const subtaskCheck = await db.query('SELECT id FROM subtasks WHERE id = $1', [subtaskId])
    if (subtaskCheck.rows.length === 0) {
      return res.status(404).json({ error: '子任务不存在' })
    }
    
    await db.query(`
      UPDATE subtasks 
      SET title = $1, completed = $2
      WHERE id = $3
    `, [title, completed || false, subtaskId])
    
    res.json({ message: '子任务更新成功' })
  } catch (error) {
    console.error('更新子任务失败:', error)
    res.status(500).json({ error: '更新子任务失败' })
  }
})

// 切换子任务完成状态
router.patch('/subtasks/:subtaskId/toggle', async (req: Request, res: Response) => {
  try {
    const { subtaskId } = req.params
    const db = getDatabase()
    
    // 检查子任务是否存在
    const subtaskCheck = await db.query('SELECT id FROM subtasks WHERE id = $1', [subtaskId])
    if (subtaskCheck.rows.length === 0) {
      return res.status(404).json({ error: '子任务不存在' })
    }
    
    await db.query('UPDATE subtasks SET completed = NOT completed WHERE id = $1', [subtaskId])
    
    res.json({ message: '子任务状态更新成功' })
  } catch (error) {
    console.error('更新子任务状态失败:', error)
    res.status(500).json({ error: '更新子任务状态失败' })
  }
})

// 删除子任务
router.delete('/subtasks/:subtaskId', async (req: Request, res: Response) => {
  try {
    const { subtaskId } = req.params
    const db = getDatabase()
    
    // 检查子任务是否存在
    const subtaskCheck = await db.query('SELECT id FROM subtasks WHERE id = $1', [subtaskId])
    if (subtaskCheck.rows.length === 0) {
      return res.status(404).json({ error: '子任务不存在' })
    }
    
    await db.query('DELETE FROM subtasks WHERE id = $1', [subtaskId])
    
    res.json({ message: '子任务删除成功' })
  } catch (error) {
    console.error('删除子任务失败:', error)
    res.status(500).json({ error: '删除子任务失败' })
  }
})

export { router as taskRoutes }
